package com.example.pplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {
    private EditText etUsername, etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private UserManager userManager;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        try {
            // 初始化用户管理器和SharedPreferences
            userManager = new UserManager(this);
            sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);

            // 检查是否已登录
            if (sharedPreferences.contains("current_user_id")) {
                long userId = sharedPreferences.getLong("current_user_id", -1);
                if (userId != -1) {
                    startMainActivity();
                    finish();
                    return;
                }
            }

            // 初始化视图
            initViews();
        } catch (Exception e) {
            Toast.makeText(this, "应用初始化失败，请重试", Toast.LENGTH_SHORT).show();
            Log.e("LoginActivity", "初始化错误", e);
            finish();
        }
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        tvRegister = findViewById(R.id.tv_register);

        // 设置点击事件
        btnLogin.setOnClickListener(v -> attemptLogin());
        tvRegister.setOnClickListener(v -> startActivity(new Intent(this, RegisterActivity.class)));
    }

    private void attemptLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 验证输入
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            // 验证登录
            long userId = userManager.getUserIdByUsernameAndPassword(username, password);
            if (userId != -1) {
                // 保存用户ID到SharedPreferences
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putLong("current_user_id", userId);
                editor.apply();

                startMainActivity();
                finish();
            } else {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "登录失败，请重试", Toast.LENGTH_SHORT).show();
            Log.e("LoginActivity", "登录错误", e);
        }
    }

    private void startMainActivity() {
        try {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "无法启动主页面", Toast.LENGTH_SHORT).show();
            Log.e("LoginActivity", "启动MainActivity错误", e);
        }
    }
}